package com.dnjn.happiness.survey.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.survey.domain.Question;
import com.dnjn.happiness.survey.domain.SurveyIntervalScore;
import com.dnjn.happiness.survey.domain.SurveyRecord;
import com.dnjn.happiness.survey.domain.SurveyTemplate;
import com.dnjn.happiness.survey.domain.TikuTags;
import com.dnjn.happiness.survey.domain.vo.SurveyTemplateVO;
import com.dnjn.happiness.survey.service.IQuestionService;
import com.dnjn.happiness.survey.service.ISurveyIntervalScoreService;
import com.dnjn.happiness.survey.service.ISurveyRecordService;
import com.dnjn.happiness.survey.service.ISurveyTemplateService;
import com.dnjn.happiness.survey.service.ITikuService;
import com.dnjn.happiness.survey.service.ITikuTagsService;
import com.dnjn.happiness.system.api.RemoteUserService;
import com.dnjn.happiness.system.api.domain.SysUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 问卷Controller
 *
 * @author happiness
 * @date 2023-10-23
 */
@Tag(name = "survey survey 问卷-模板", description = "问卷")
@RestController
@RequestMapping("/surveyTemplate")
public class SurveyTemplateController extends BaseController {
    @Autowired
    private ISurveyTemplateService surveyTemplateService;

    @Autowired
    private ITikuTagsService tikuTagsService;

    @Autowired
    private ITikuService tikuService;

    @Autowired
    private ISurveyRecordService recordService;

    @Autowired
    private IQuestionService questionService;

    @Autowired
    private RemoteUserService userService;

    @Autowired
    private ISurveyIntervalScoreService intervalScoreService;


    /**
     * 新增内置问卷模板
     */
    @Log(title = "新增内置问卷模板", businessType = BusinessType.INSERT)
    @RequiresPermissions("@ss.hasPermi('survey:surveyTemplate:add')")
    @PostMapping("/addSurvey")
    @Operation(summary = "新增内置问卷模板")
    public AjaxResult saveBuiltInSurvey(@RequestBody SurveyTemplate survey) {
        Assert.notNull(survey.getSurveyTitle(), "问卷标题不能为空");
        survey.setCreateBy(SecurityUtils.getUsername());
        int i = surveyTemplateService.saveBuiltInSurvey(survey);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("survey", survey);
        return ajax;
    }

    /**
     * 新增自定义问卷模板
     */
    @Log(title = "问卷", businessType = BusinessType.INSERT)
    @RequiresPermissions("@ss.hasPermi('survey:surveyTemplate:add')")
    @PostMapping("/addCustomSurvey")
    @Operation(summary = "新增自定义问卷模板")
    public AjaxResult addCustomSurvey(@RequestBody SurveyTemplateVO vo) {
        SurveyTemplate survey = new SurveyTemplate();
        BeanUtils.copyPropsIgnoreNull(vo, survey);
        Assert.notNull(survey.getSurveyTitle(), "问卷标题不能为空");
        survey.setCreateBy(SecurityUtils.getUsername());
        return surveyTemplateService.addCustomSurvey(survey);
    }

    /**
     * 修改自定义问卷
     */
    @Log(title = "修改自定义问卷editCustomSurvey", businessType = BusinessType.UPDATE)
    @PutMapping("/editCustomSurvey")
    @Operation(description = "修改自定义问卷editCustomSurvey")
    @RequiresPermissions("@ss.hasPermi('survey:surveyTemplate:edit')")
    public AjaxResult editCustomSurvey(@RequestBody SurveyTemplateVO vo) {
        SurveyTemplate survey = new SurveyTemplate();
        BeanUtils.copyPropsIgnoreNull(vo, survey);
        Assert.notNull(survey.getSurveyTitle(), "问卷标题不能为空");
        int i = surveyTemplateService.editCustomSurvey(survey);
        return toAjax(i);
    }

    /**
     * 根据问卷id查询问卷
     */
    @Operation(summary = "后台根据问卷id查询问卷")
    @GetMapping("/getTemplateById/{surveyId}")
    @RequiresPermissions("@ss.hasPermi('survey:surveyTemplate:query')")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getTemplateById(@PathVariable Long surveyId) {
        SurveyTemplate survey = surveyTemplateService.getTemplateById(surveyId);
        return success(survey);
    }


    //发起问卷
    @Log(title = "问卷", businessType = BusinessType.INSERT)
    @PostMapping("/addSurveyWX")
    @Operation(summary = "我的-发起问卷-发起问卷-小程序", description = "开始时间dateStart;结束时间dateEnd,问卷标题surveyTitle不能为空")
    public AjaxResult addSurvey(@RequestBody SurveyTemplate survey) {
        Assert.notNull(survey.getSurveyTitle(), "问卷标题不能为空");
        survey.setCreateBy(SecurityUtils.getUsername());
        int i = surveyTemplateService.saveBuiltInSurvey(survey);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("survey", survey);
        return ajax;
    }

    @PostMapping("/querySurveyByTikuTagsId")
    @Operation(summary = "问卷", description = "userId-个人详情时间轴问卷记录-只传userId; ② 我的问卷-问卷记录-查看我需要参与的问卷 必传 watchId, 可选:recordStatus(Y|N)")
    public AjaxResult querySurveyByTikuTagsId(@RequestBody SurveyTemplate domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page<SurveyTemplate> list = surveyTemplateService.selectPageSurvey(domain, Page.of(current, size).addOrder(OrderItem.desc("survey_id")));
        return success(list);

    }

    // 小程序 我的 -我的问卷
    @PostMapping("/querySurveyByUserId")
    @Operation(summary = "问卷", description = "userId-个人详情时间轴问卷记录-只传userId; ② 我的问卷-问卷记录-查看我需要参与的问卷 必传 watchId, 可选:recordStatus(Y|N)")
    public AjaxResult querySurveyByUserId(@RequestBody SurveyTemplate domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page<SurveyTemplate> list = surveyTemplateService.selectPageSurvey(domain, Page.of(current, size).addOrder(OrderItem.desc("survey_id")));


        return success(list);

    }

    @PostMapping("/endsurveyId")
    @Operation(summary = "我的-我的问卷-结束问卷", description = "surveyId 问卷id")
    public AjaxResult endSurveyId(@Parameter Long surveyId) {
        surveyTemplateService.endSurveyId(surveyId);
        return success();
    }

    @PostMapping("/issuedSurveyId")
    @Operation(summary = "我的-我的问卷-下发问卷", description = "surveyId 问卷id")
    public AjaxResult issuedSurveyId(@Parameter Long surveyId) {

        List<SurveyRecord> list = recordService.lambdaQuery().eq(SurveyRecord::getSurveyId, surveyId).eq(SurveyRecord::getDeleted, "0").list();
        if (list.size() > 0) {
            boolean update = surveyTemplateService.lambdaUpdate().eq(SurveyTemplate::getSurveyId, surveyId).set(SurveyTemplate::getIssuedStatus, "1").update();
            if (update) {
                surveyTemplateService.lambdaUpdate().eq(SurveyTemplate::getSurveyId, surveyId).set(SurveyTemplate::getSurveyStatus, "PROCESSING").update();
            }

            SurveyTemplate one = surveyTemplateService.lambdaQuery().eq(SurveyTemplate::getSurveyId, surveyId).one();
        } else {
            return AjaxResult.success("没有答题人");
        }

        return success();

    }

    /**
     * 根据问卷id查询问卷
     */
    @Operation(summary = "根据问卷id查询问卷")
    @GetMapping("/{surveyId}")
    @RequiresPermissions("survey:surveyTemplate:query")
    public AjaxResult get(@PathVariable Long surveyId) {
        SurveyTemplate survey = surveyTemplateService.getSurveyTemplateById(surveyId);

        return success(survey);
    }

    /**
     * 修改内置问卷
     */
    @Log(title = "问卷", businessType = BusinessType.UPDATE)
    @PutMapping
    @RequiresPermissions("@ss.hasPermi('survey:surveyTemplate:edit')")
    public AjaxResult edit(@RequestBody SurveyTemplate survey) {
        Assert.notNull(survey.getSurveyTitle(), "问卷标题不能为空");
        int i = surveyTemplateService.updateSurvey(survey);
        return toAjax(i);
    }

    /**
     * 删除问卷
     */
    @Log(title = "问卷", businessType = BusinessType.UPDATE)
    @RequiresPermissions("survey:surveyTemplate:remove")
    @DeleteMapping("/{surveyId}")
    public AjaxResult deleteSurvey(@PathVariable Long surveyId) {
        Assert.notNull(surveyId, "问卷Id不能为空");
        Boolean flag = surveyTemplateService.deleteSurvey(surveyId);
        if (flag) {
            return success("删除成功");
        } else {
            return error("删除失败");
        }
    }

    /**
     * 查询所有的问卷，根据题库类型id
     */
    @GetMapping("/getSurveyTemplatesByTikuTagesId1/{tikuTagsId}")
    @RequiresPermissions("survey:surveyTemplate:query")
    public AjaxResult getSurveyTemplatesByTikuTagesId1(@PathVariable Long tikuTagsId) {
        List<SurveyTemplate> surveyTemplateList = surveyTemplateService.lambdaQuery().eq(SurveyTemplate::getTikuTagsId, tikuTagsId).eq(SurveyTemplate::getDeleted, "0").list();
        return AjaxResult.success(surveyTemplateList);
    }

    /**
     * wx查询所有的问卷，根据题库类型id
     */
    @GetMapping("/getSurveyTemplatesByTikuTagesId/{tikuTagsId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getSurveyTemplatesByTikuTagesId(@PathVariable Long tikuTagsId) {
        List<SurveyTemplate> surveyTemplateList = surveyTemplateService.lambdaQuery().eq(SurveyTemplate::getTikuTagsId, tikuTagsId).eq(SurveyTemplate::getDeleted, "0").list();
        return AjaxResult.success(surveyTemplateList);
    }


}
